#include <rtthread.h>
#include "board.h"
#include <rtdevice.h>

#define ESC_CMD_BUFFER_LEN 16

#define DMA_BUFFER_SIZE (ESC_CMD_BUFFER_LEN * 4 + 8)

static void RCC_Configuration(void)
{
    /* Enable GPIO clocks */
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOC, ENABLE);
    /* Enable DMA clocks */
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA1, ENABLE);
    /* Enable TIM GPIO clocks */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
}
static void GPIO_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_TIM3);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_TIM3);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource8, GPIO_AF_TIM3);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource9, GPIO_AF_TIM3);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;

    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_Init(GPIOC, &GPIO_InitStructure);
}

static void TIM_Configuration(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure = {0};
    TIM_OCInitTypeDef TIM_OCInitStructure = {0};

    TIM_TimeBaseStructure.TIM_Period = 166;
    TIM_TimeBaseStructure.TIM_Prescaler = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = 0;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;

    TIM_OC1Init(TIM3, &TIM_OCInitStructure);
    TIM_OC2Init(TIM3, &TIM_OCInitStructure);
    TIM_OC3Init(TIM3, &TIM_OCInitStructure);
    TIM_OC4Init(TIM3, &TIM_OCInitStructure);

    TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
    TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
    TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
    TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);

    TIM_DMAConfig(TIM3, TIM_DMABase_CCR1, TIM_DMABurstLength_4Transfers);
    TIM_DMACmd(TIM3, TIM_DMA_Update, ENABLE);
    TIM_ARRPreloadConfig(TIM3, ENABLE);
    TIM_Cmd(TIM3, ENABLE);
    // TIM_CtrlPWMOutputs(TIM3, ENABLE);
}

static void DMA_Configuration(void)
{
    DMA_InitTypeDef DMA_InitStructure;

    DMA_DeInit(DMA1_Stream2);
    DMA_InitStructure.DMA_Channel = DMA_Channel_5;
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&TIM3->DMAR;
    DMA_InitStructure.DMA_Memory0BaseAddr = 0;
    DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
    DMA_InitStructure.DMA_BufferSize = 1;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
    DMA_InitStructure.DMA_Priority = DMA_Priority_High;
    DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
    DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull;
    DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
    DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
    DMA_Init(DMA1_Stream2, &DMA_InitStructure);

    DMA_ClearFlag(DMA1_Stream2, DMA_FLAG_TCIF2);
    DMA_ITConfig(DMA1_Stream2, DMA_IT_TC, ENABLE);
}

static void NVIC_Configuration(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;

    /* Enable the USART1 Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = DMA1_Stream2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    NVIC_EnableIRQ(DMA1_Stream2_IRQn);
}

static int d_init(struct rt_pwm_t *pwm)
{
    RCC_Configuration();
    GPIO_Configuration();
    TIM_Configuration();
    DMA_Configuration();
    NVIC_Configuration();

    return 0;
}

static void d_deinit(struct rt_pwm_t *pwm)
{
}

static int d_config(rt_pwm_t *pwm, struct pwm_configuration *cfg)
{
    return 0;
}

static void d_get_cap(rt_pwm_t *pwm, struct pwm_caps *cap)
{
    cap->flags = PWM_CF_MCHANNEL_SYNC_OUT | PWM_CF_QUEUED_PULSE;
    cap->num_channels = 4;
    rt_memcpy(cap->platform, "stm32-f4xx", 11);
}

static const struct pwm_base_ops _ops = {
    .init = d_init,
    .deinit = d_deinit,
    .config = d_config,
    .get_cap = d_get_cap,
};

static int d_reqbuf(rt_pwm_t *pwm, struct pwm_io_buffer *buf, unsigned pulse_count)
{
    buf->vaddr = rt_malloc(pulse_count * 4);
    if (!buf->vaddr)
    {
        return -1;
    }

    buf->length = pulse_count * 4;
    buf->paddr = buf->vaddr;

    return 0;
}

static void d_prepare(rt_pwm_t *pwm, struct pwm_io_buffer *buf)
{
}

static int d_start(rt_pwm_t *pwm, struct pwm_io_buffer *buf)
{
    DMA_MemoryTargetConfig(DMA1_Stream2, (uint32_t)buf->paddr, DMA_Memory_0);
    DMA_SetCurrDataCounter(DMA1_Stream2, DMA_BUFFER_SIZE);
    DMA_Cmd(DMA1_Stream2, ENABLE);

    return 0;
}

static const struct pwm_ext_ops _eops = {
    .reqbuf = d_reqbuf,
    .prepare = d_prepare,
    .start = d_start,
};

static rt_pwm_t _pwm0;
void DMA1_Stream2_IRQHandler(void)
{
    if (DMA_GetFlagStatus(DMA1_Stream2, DMA_FLAG_TCIF2))
    {
        DMA_ClearFlag(DMA1_Stream2, DMA_FLAG_TCIF2);
        rt_pwm_buffer_done(&_pwm0);
    }
}

int pwm_drv_init(void)
{
    _pwm0.bops = &_ops;
    _pwm0.eops = &_eops;

    rt_hw_pwm_register(&_pwm0, "pwm0", 0);

    return 0;
}
INIT_DEVICE_EXPORT(pwm_drv_init);
